var util = require('../../utils/util.js')
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
var reload = true;
var page = 1;
var hasMore = true;
var loadingMore = false;

var SDKVersion = '';
var status = true;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgDomain: app.globalData.imgDomain,

    classlysData: '',

    zxsData: [],
    hasData: true,

    uid: 0,
    token: '',
    openid: '',
    canEdit: 0,

    bottom_nav_data: [],
    isIphone_x: false,
    nav_bgColor: '#ffffff',

    shouqian_phone: '',
    colorSet: '',
    wz_item_img_w_1: 300,

    hide_commentview: true,

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    var tc = app.get_tc();
    var titlename = tc == 1 ? '猎头咨询' : '猎头咨询';
    wx.setNavigationBarTitle({
      title: titlename,
    }); 
    wx.showLoading({
      title: '加载中',
      mask: 'true'
    })

    page = 1;
    hasMore = true;
    loadingMore = false;

    var that = this;

    //获取颜色配置
    app.getColorSetData(function (color) {
      that.setData({
        colorSet: color,
      })
      that.resetNavColor();
    });

    //初始化底部导航
    var b_nav_data = app.getBottomNavData('zixune/zixune', function (data) {
      that.setData({
        bottom_nav_data: data,
        nav_bgColor: data[0].bgcolor,
      });
    });

    wx.getSystemInfo({
      success: function (res) {
        SDKVersion = res.SDKVersion;
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          tc: app.get_tc(),
          isIphone_x: isIphone_x,
          screen_h: res.windowHeight,
          wz_item_img_w_1: res.windowWidth - 25
        });
      }
    })

    reload = true;
    //当前登录用户信息
    app.LoginUserInfo(function (res) {
      var authFail = res == -1;//用户拒绝授权
      if (!authFail) {
        //更新数据
        that.setData({
          uid: res.uid,
          token: res.token,
          openid: res.wxsmall_openid
        });
      }

    });
    //获取关于等信息
    app.getAllAbout('shouqian', function (res) {
      that.setData({
        shouqian_phone: res
      })
    });
    //读取文字分类
    this.loadZXS(1);
  },

  load: function (refresh) {
    var that = this;
    var dataType = this.data.topicType;
    var page = that.data.page;
    var num = that.data.limit;
    if (refresh && that.data.data.length > 0) {
      page = 1;
      num = that.data.data.length;
      that.setData({
        page: page
      })
    }
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "topiclist",
        orgid: util.orgid,
        topictype: 1,
        albumid: '',
        // toporder: 1,
        page: page,
        num: num
      },
      success: function (responseData) {
        console.log("所有数据列表：", responseData);
        var data = responseData.data;
        var newData;
        if (data && !data.msg) {
          for (var i = 0; i < data.length; i++) {
            data[i].message = app.parseHTMLText(data[i].message);
            var date = new Date(data[i].dateline * 1000);
            data[i].formattime = util.formatTime(date, '-', ':');
            //处理用户等级
            var level = 0;
            var num = data[i].user.scorenum
            data[i].user.level = 0;
            data[i].user.junfen = 0;
            if (num > 0) {
              var fen = data[i].user.scorecoin;
              var junfen = (fen / num).toFixed(1);
              if (junfen >= 4) {
                if (num >= 10000) {
                  level == 5;
                } else if (num >= 5000) {
                  level == 4;
                } else if (num >= 3000) {
                  level == 3;
                } else if (num >= 500) {
                  level == 2;
                } else if (num >= 100) {
                  level == 1;
                }
              } else if (junfen >= 3) {
                if (num >= 10000) {
                  level == 4;
                } else if (num >= 5000) {
                  level == 3;
                } else if (num >= 3000) {
                  level == 2;
                } else if (num >= 100) {
                  level == 1;
                }
              } else if (junfen >= 2) {
                if (num >= 10000) {
                  level == 3;
                } else if (num >= 5000) {
                  level == 2;
                } else if (num >= 100) {
                  level == 1;
                }
              } else {
                if (num >= 10000) {
                  level == 2;
                } else if (num >= 100) {
                  level == 1;
                }
              }

              data[i].user.level = level;
              data[i].user.junfen = junfen;
            }
            if (that.data.latitude) {
              //计算直线距离
              var distanStr = '';
              var distan = app.getDistance(that.data.latitude, that.data.longitude, data[i].lat, data[i].lon);
              if (distan > 1000) {
                distanStr = (distan / 1000).toFixed(2) + 'km';
              } else {
                distanStr = distan.toFixed(0) + 'm';
              }
              data[i].distanse = distanStr;
            }
            //处评论者信息
            var peoples = data[i].people;
            var comments = data[i].comments;
            for (var j = 0; j < comments.length; j++) {
              var commentUserId = comments[j].author.uid;
              if (peoples.indexOf(commentUserId) >= 0) {
                commrents[j].buied = true;
              }
            }
          }
          if (refresh) {
            newData = data
          } else {
            newData = that.data.data.concat(data);
          }
          that.setData({
            data: newData,
            hasLoadding: false
          });
        } else {
          that.setData({
            hasMore: false
          });
        }
        if (that.data.data.length <= 0) {
          that.setData({
            noData: true
          })
        }
        wx.hideLoading();
      }
    });


  },

  loadMore: function (e) {
    if (hasMore && !loadingMore) {
      loadingMore = true;
      page++;
      this.loadZXS(page);
    } else {
      console.log("没有更多了");
    }
  },

  // 读取动态 （近况）
  loadZXS: function (cpage) {
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "getzxs",
      orgid: util.orgid,
      page: cpage,
      num: 10
    }
    util.api({
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("咨询师数据：", result);
        if (!result.msg) {
          // result.forEach(function (m, i) {
          //   if (m.photos) {
          //     result[i].photosData = m.photos.split(",");
          //   }
          //   result[i].message = app.parseHTMLText(m.message);
          // });

          if (cpage <= 1) {
            that.setData({
              zxsData: result
            });

          } else {

            that.setData({
              zxsData: that.data.zxsData.concat(result)
            });

          }
        } else {
          if (cpage <= 1) {

            that.setData({
              zxsData: []
            });

          }

          hasMore = false;


        }
        loadingMore = false;

        if (that.data.zxsData.length <= 0) {
          that.setData({
            hasData: false
          })
        } else {
          that.setData({
            hasData: true
          })
        }
        wx.hideLoading();
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },


  goAtherPage: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.navigateTo({ url: url })
  },
  goAtherPageRedirect: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.redirectTo({ url: url })
  },

  //保存formId
  submitFormId: function (e) {
    app.saveFormId(e.detail.formId);

    var path = e.detail.value.nav_path;
    if (path) {
      wx.redirectTo({ url: path })
    }
  },
  makeCallPhone: function (e) {
    var phoneNum = e.currentTarget.dataset.number;
    console.log("phoneNum:" + phoneNum);
    wx.makePhoneCall({
      phoneNumber: phoneNum,
      success: function (e) {
        console.log("make call success:", JSON.stringify(e));
      },
      fail: function (e) {
        console.log("make call fail:", JSON.stringify(e));
      }
    })
  },
  goMapView: function (e) {
    var addr = e.currentTarget.dataset.addr;
    var lat = parseFloat(addr.lat);
    var lon = parseFloat(addr.lon);
    wx.openLocation({
      latitude: lat,
      longitude: lon,
      scale: 20,
      name: addr.name,
      address: addr.address
    })
  },
  showCommentView: function (e) {
    this.setData({
      hide_commentview: false,
      data_id: e.currentTarget.dataset.id
    })
  },
  hideCommentView: function () {
    this.setData({
      hide_commentview: true
    })
  },

  resetNavColor: function () {
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';
    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },

  //页面分享
  onShareAppMessage: function () {
    var that = this;
    var inviteuid = that.data.loginuid ? that.data.loginuid : '';
    console.log("分享id" + inviteuid);
    if (util.orgid == '15671') {
      return {
        title: '求职，企业招聘，人才培训……壹号人才欢迎您',
        path: '/pages/zixune/zixune?&inviteuid=' + inviteuid
      };
    } else {
      return {
        title: that.data.org_name,
        path: '/pages/index/index?&inviteuid=' + inviteuid
      };
    }
  },
})